package cn.sytton.taffecloud.serivce.auth.security.factory;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.sytton.taffecloud.serivce.auth.model.AuthUserEntity;
import cn.sytton.taffecloud.serivce.auth.mapper.SecurityMapper;
import cn.sytton.taffecloud.serivce.auth.security.model.SecurityUser;
import cn.sytton.taffecloud.common.base.security.LoginUser;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Date;

/**
 * UserDetailsService创建工厂
 *
 * @author skyrock
 */
@Component
public class UserDetailFactory {

    @Resource
    private SecurityMapper securityMapper;

    public SecurityUser create(AuthUserEntity authUser) {
        if (authUser.getUserStatus() != 1) {
            throw new BadCredentialsException(new MessageFormat("账号 {0} 已禁用").format(new Object[] { authUser.getLoginName() }));
        }
        if (authUser.getExpiryDate() != null){
            if ( authUser.getExpiryDate().before(new Date()) ){
                throw new BadCredentialsException(new MessageFormat("账号 {0} 已过有效期").format(new Object[] { authUser.getLoginName() }));
            }
        }

        LoginUser user = new LoginUser();
        user.setUserId(authUser.getUserId());
        user.setUserCode(authUser.getUserCode());
        user.setLoginName(authUser.getLoginName());
        user.setUserName(authUser.getUserName());
        user.setPassword(authUser.getPassword());
        user.setEmail(authUser.getEmail());
        user.setCellphone(authUser.getCellphone());
        user.setDeptId("");
        user.setUserType(authUser.getUserType().toString());
        user.setUserStatus(authUser.getUserStatus().toString());
        user.setExpireDate(authUser.getExpiryDate());
        user.setUserRoles(securityMapper.findRoleIds(authUser.getUserId()));
        user.setLoginTimeStamp(System.currentTimeMillis());

        HttpServletRequest request = cn.sytton.taffecloud.common.servlet.util.ServletUtil.getRequest();
        if (request != null) {
            user.setIp(ServletUtil.getClientIP(request));
            user.setLoginLocation(""); //todo 设置登录位置
            UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
            if (userAgent != null) {
                user.setBrowser(userAgent.getBrowser().getName());
                user.setOs(userAgent.getOs().getName());
            }
        }
        return new SecurityUser(user);
    }
}
